<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialogVisible"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <!-- 商品列表区域 -->
      <tree-table
        class="tree-table"
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        border
      >
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted == false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: lightgreen"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level == 1" type="success"
            >二级</el-tag
          >
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="showEditDislog(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="deleteCateById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[5, 7, 10, 15]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加商品分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <!-- 联级选择器 optinos为数据源 props为配置项 -->
          <el-cascader
            checkStrictly
            :props="cascaderProps"
            clearable
            v-model="selectedKeys"
            :options="ParentCateList"
            expand-trigger="hover"
            @change="ParentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改商品分类对话框 -->
    <el-dialog
      title="修改分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClose"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //商品信息列表
      cateList: [],
      //参数列表
      queryinfo: {
        //展示所有商品列表
        type: 3,
        //当前页面
        pagenum: 1,
        //每页显示几条商品信息
        pagesize: 5,
      },
      //总数据条数
      total: 0,
      //添加商品分类对话框显示隐藏
      addCateDialogVisible: false,
      addCateForm: {
        //父级分类id
        cat_pid: 0,
        //要添加的分类名称
        cat_name: "",
        //分类等级
        cat_level: 0,
      },
      //父级分类的列表
      ParentCateList: [],
      //指定级联新增器的配置对象
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      //选中的父级分类id数组
      selectedKeys: [],
      //修改分类对话框显示与隐藏
      editCateDialogVisible: false,
      //修改分类的表单数据对象
      editCateForm: {},
      //tree-table列的定义
      columns: [
        { label: "分类名称", prop: "cat_name" },
        //将当前列定义为模板列，名称为isok
        { label: "是否有效", type: "template", template: "isok" },
        { label: "排序", type: "template", template: "order" },
        { label: "操作", type: "template", template: "opt" },
      ],
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
        ],
      },
      editCateRules:{
          cat_name:[
            { required: true, message: "请输入分类名称", trigger: "blur" },
            { min: 2, max: 6, message: "长度在 2 到 6 个字符", trigger: "blur" },
          ]
      }
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryinfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }
      //商品数据在result对象中
      this.cateList = res.data.result;
      //商品信息主条数
      this.total = res.data.total;
    },
    //分页器
    handleSizeChange(val) {
      this.queryinfo.pagesize = val;
      this.getCateList();
    },
    //分页器
    handleCurrentChange(val) {
      this.queryinfo.pagenum = val;
      this.getCateList();
    },
    //展示添加分类对话框
    showAddCateDialogVisible() {
      this.getParentCateList();
      this.addCateDialogVisible = true;
    },
    //获取父级分类数据列表
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取父级分类失败");
      }
      this.ParentCateList = res.data;
    },
    ParentCateChanged() {
      if (this.selectedKeys.length > 0) {
        //父级分类的id
        this.addCateForm.cat_pid =
          this.selectedKeys[this.selectedKeys.length - 1];
        //为当前的分类的等级赋值
        this.addCateForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        //为当前的分类的等级赋值
        this.addCateForm.cat_level = 0;
      }
    },
    //监听添加分类对话框
    addCateDialogClose() {
      this.$refs.addCateFormRef.resetFields();
      this.selectedKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    addCate() {
      this.$refs.addCateFormRef.validate(async (vaild) => {
        if (!vaild) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        if (res.meta.status !== 201) {
          return this.$message.error("添加分类失败");
        }
        this.$message.success("添加分类成功");
        this.addCateDialogVisible = false;
        this.getCateList();
      });
    },
    //根据id删除商品分类
    async deleteCateById(id) {
      const resultConfirm = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //如果用户确认删除，返回为字符串comfirm
      //如果用户取消删除，返回字符串cancel
      if (resultConfirm !== "confirm") {
        return this.$message.info("已取消删除");
      }
      const { data: res } = await this.$http.delete("categories/" + id);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("删除分类失败");
      }
      this.$message.success("删除分类成功");
      this.getCateList();
    },
    //  先查询 再修改分类信息
    async showEditDislog(id) {
      const { data: res } = await this.$http.get("categories/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("查询分类信息失败");
      }
      this.editCateForm = res.data;
      this.editCateDialogVisible = true;
    },
    //监听分类修改的对话框关闭事件
    editCateDialogClose() {
      this.$refs.editCateFormRef.resetFields();
    },
    //修改分类信息
    editCate() {
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        }
        const { data: res } = await this.$http.put(
          "categories/" + this.editCateForm.cat_id,
          {cat_name:this.editCateForm.cat_name}
        );
        if (res.meta.status !== 200) {
          this.$message.error("修改分类失败");
        }
        //隐藏修改对话框
        this.editCateDialogVisible = false;
        //刷新列表
        this.getCateList();
        this.$message.success("修改分类成功");
      });
    },
  },
};
</script>

<style lang="less" scoped>
.tree-table {
  margin-top: 10px;
}
.el-cascader {
  width: 100%;
}
</style>

